home *** CD-ROM | disk | FTP | other *** search
/ Clickx 47 / Clickx 47.iso / assets / software / Miro_Installer.exe / Miro_Downloader.exe / urllib2.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-01-10  |  40.8 KB  |  1,345 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''An extensible library for opening URLs using a variety of protocols
  5.  
  6. The simplest way to use this module is to call the urlopen function,
  7. which accepts a string containing a URL or a Request object (described
  8. below).  It opens the URL and returns the results as file-like
  9. object; the returned object has some extra methods described below.
  10.  
  11. The OpenerDirector manages a collection of Handler objects that do
  12. all the actual work.  Each Handler implements a particular protocol or
  13. option.  The OpenerDirector is a composite object that invokes the
  14. Handlers needed to open the requested URL.  For example, the
  15. HTTPHandler performs HTTP GET and POST requests and deals with
  16. non-error returns.  The HTTPRedirectHandler automatically deals with
  17. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  18. deals with digest authentication.
  19.  
  20. urlopen(url, data=None) -- basic usage is the same as original
  21. urllib.  pass the url and optionally data to post to an HTTP URL, and
  22. get a file-like object back.  One difference is that you can also pass
  23. a Request instance instead of URL.  Raises a URLError (subclass of
  24. IOError); for HTTP errors, raises an HTTPError, which can also be
  25. treated as a valid response.
  26.  
  27. build_opener -- function that creates a new OpenerDirector instance.
  28. will install the default handlers.  accepts one or more Handlers as
  29. arguments, either instances or Handler classes that it will
  30. instantiate.  if one of the argument is a subclass of the default
  31. handler, the argument will be installed instead of the default.
  32.  
  33. install_opener -- installs a new opener as the default opener.
  34.  
  35. objects of interest:
  36. OpenerDirector --
  37.  
  38. Request -- an object that encapsulates the state of a request.  the
  39. state can be a simple as the URL.  it can also include extra HTTP
  40. headers, e.g. a User-Agent.
  41.  
  42. BaseHandler --
  43.  
  44. exceptions:
  45. URLError-- a subclass of IOError, individual protocols have their own
  46. specific subclass
  47.  
  48. HTTPError-- also a valid HTTP response, so you can treat an HTTP error
  49. as an exceptional event or valid response
  50.  
  51. internals:
  52. BaseHandler and parent
  53. _call_chain conventions
  54.  
  55. Example usage:
  56.  
  57. import urllib2
  58.  
  59. # set up authentication info
  60. authinfo = urllib2.HTTPBasicAuthHandler()
  61. authinfo.add_password(\'realm\', \'host\', \'username\', \'password\')
  62.  
  63. proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
  64.  
  65. # build a new opener that adds authentication and caching FTP handlers
  66. opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
  67.  
  68. # install it
  69. urllib2.install_opener(opener)
  70.  
  71. f = urllib2.urlopen(\'http://www.python.org/\')
  72.  
  73.  
  74. '''
  75. import base64
  76. import hashlib
  77. import httplib
  78. import mimetools
  79. import os
  80. import posixpath
  81. import random
  82. import re
  83. import socket
  84. import sys
  85. import time
  86. import urlparse
  87. import bisect
  88.  
  89. try:
  90.     from cStringIO import StringIO
  91. except ImportError:
  92.     from StringIO import StringIO
  93.  
  94. from urllib import unwrap, unquote, splittype, splithost, quote, addinfourl, splitport, splitgophertype, splitquery, splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue
  95. from urllib import localhost, url2pathname, getproxies
  96. __version__ = sys.version[:3]
  97. _opener = None
  98.  
  99. def urlopen(url, data = None):
  100.     global _opener
  101.     if _opener is None:
  102.         _opener = build_opener()
  103.     
  104.     return _opener.open(url, data)
  105.  
  106.  
  107. def install_opener(opener):
  108.     global _opener
  109.     _opener = opener
  110.  
  111.  
  112. class URLError(IOError):
  113.     
  114.     def __init__(self, reason):
  115.         self.args = (reason,)
  116.         self.reason = reason
  117.  
  118.     
  119.     def __str__(self):
  120.         return '<urlopen error %s>' % self.reason
  121.  
  122.  
  123.  
  124. class HTTPError(URLError, addinfourl):
  125.     '''Raised when HTTP error occurs, but also acts like non-error return'''
  126.     __super_init = addinfourl.__init__
  127.     
  128.     def __init__(self, url, code, msg, hdrs, fp):
  129.         self.code = code
  130.         self.msg = msg
  131.         self.hdrs = hdrs
  132.         self.fp = fp
  133.         self.filename = url
  134.         if fp is not None:
  135.             self._HTTPError__super_init(fp, hdrs, url)
  136.         
  137.  
  138.     
  139.     def __str__(self):
  140.         return 'HTTP Error %s: %s' % (self.code, self.msg)
  141.  
  142.  
  143.  
  144. class GopherError(URLError):
  145.     pass
  146.  
  147. _cut_port_re = re.compile(':\\d+$')
  148.  
  149. def request_host(request):
  150.     '''Return request-host, as defined by RFC 2965.
  151.  
  152.     Variation from RFC: returned value is lowercased, for convenient
  153.     comparison.
  154.  
  155.     '''
  156.     url = request.get_full_url()
  157.     host = urlparse.urlparse(url)[1]
  158.     if host == '':
  159.         host = request.get_header('Host', '')
  160.     
  161.     host = _cut_port_re.sub('', host, 1)
  162.     return host.lower()
  163.  
  164.  
  165. class Request:
  166.     
  167.     def __init__(self, url, data = None, headers = { }, origin_req_host = None, unverifiable = False):
  168.         self._Request__original = unwrap(url)
  169.         self.type = None
  170.         self.host = None
  171.         self.port = None
  172.         self.data = data
  173.         self.headers = { }
  174.         for key, value in headers.items():
  175.             self.add_header(key, value)
  176.         
  177.         self.unredirected_hdrs = { }
  178.         if origin_req_host is None:
  179.             origin_req_host = request_host(self)
  180.         
  181.         self.origin_req_host = origin_req_host
  182.         self.unverifiable = unverifiable
  183.  
  184.     
  185.     def __getattr__(self, attr):
  186.         if attr[:12] == '_Request__r_':
  187.             name = attr[12:]
  188.             if hasattr(Request, 'get_' + name):
  189.                 getattr(self, 'get_' + name)()
  190.                 return getattr(self, attr)
  191.             
  192.         
  193.         raise AttributeError, attr
  194.  
  195.     
  196.     def get_method(self):
  197.         if self.has_data():
  198.             return 'POST'
  199.         else:
  200.             return 'GET'
  201.  
  202.     
  203.     def add_data(self, data):
  204.         self.data = data
  205.  
  206.     
  207.     def has_data(self):
  208.         return self.data is not None
  209.  
  210.     
  211.     def get_data(self):
  212.         return self.data
  213.  
  214.     
  215.     def get_full_url(self):
  216.         return self._Request__original
  217.  
  218.     
  219.     def get_type(self):
  220.         if self.type is None:
  221.             (self.type, self._Request__r_type) = splittype(self._Request__original)
  222.             if self.type is None:
  223.                 raise ValueError, 'unknown url type: %s' % self._Request__original
  224.             
  225.         
  226.         return self.type
  227.  
  228.     
  229.     def get_host(self):
  230.         if self.host is None:
  231.             (self.host, self._Request__r_host) = splithost(self._Request__r_type)
  232.             if self.host:
  233.                 self.host = unquote(self.host)
  234.             
  235.         
  236.         return self.host
  237.  
  238.     
  239.     def get_selector(self):
  240.         return self._Request__r_host
  241.  
  242.     
  243.     def set_proxy(self, host, type):
  244.         self.host = host
  245.         self.type = type
  246.         self._Request__r_host = self._Request__original
  247.  
  248.     
  249.     def get_origin_req_host(self):
  250.         return self.origin_req_host
  251.  
  252.     
  253.     def is_unverifiable(self):
  254.         return self.unverifiable
  255.  
  256.     
  257.     def add_header(self, key, val):
  258.         self.headers[key.capitalize()] = val
  259.  
  260.     
  261.     def add_unredirected_header(self, key, val):
  262.         self.unredirected_hdrs[key.capitalize()] = val
  263.  
  264.     
  265.     def has_header(self, header_name):
  266.         if not header_name in self.headers:
  267.             pass
  268.         return header_name in self.unredirected_hdrs
  269.  
  270.     
  271.     def get_header(self, header_name, default = None):
  272.         return self.headers.get(header_name, self.unredirected_hdrs.get(header_name, default))
  273.  
  274.     
  275.     def header_items(self):
  276.         hdrs = self.unredirected_hdrs.copy()
  277.         hdrs.update(self.headers)
  278.         return hdrs.items()
  279.  
  280.  
  281.  
  282. class OpenerDirector:
  283.     
  284.     def __init__(self):
  285.         client_version = 'Python-urllib/%s' % __version__
  286.         self.addheaders = [
  287.             ('User-agent', client_version)]
  288.         self.handlers = []
  289.         self.handle_open = { }
  290.         self.handle_error = { }
  291.         self.process_response = { }
  292.         self.process_request = { }
  293.  
  294.     
  295.     def add_handler(self, handler):
  296.         added = False
  297.         for meth in dir(handler):
  298.             if meth in ('redirect_request', 'do_open', 'proxy_open'):
  299.                 continue
  300.             
  301.             i = meth.find('_')
  302.             protocol = meth[:i]
  303.             condition = meth[i + 1:]
  304.             if condition.startswith('error'):
  305.                 j = condition.find('_') + i + 1
  306.                 kind = meth[j + 1:]
  307.                 
  308.                 try:
  309.                     kind = int(kind)
  310.                 except ValueError:
  311.                     pass
  312.  
  313.                 lookup = self.handle_error.get(protocol, { })
  314.                 self.handle_error[protocol] = lookup
  315.             elif condition == 'open':
  316.                 kind = protocol
  317.                 lookup = self.handle_open
  318.             elif condition == 'response':
  319.                 kind = protocol
  320.                 lookup = self.process_response
  321.             elif condition == 'request':
  322.                 kind = protocol
  323.                 lookup = self.process_request
  324.             
  325.             handlers = lookup.setdefault(kind, [])
  326.             if handlers:
  327.                 bisect.insort(handlers, handler)
  328.             else:
  329.                 handlers.append(handler)
  330.             added = True
  331.         
  332.         if added:
  333.             bisect.insort(self.handlers, handler)
  334.             handler.add_parent(self)
  335.         
  336.  
  337.     
  338.     def close(self):
  339.         pass
  340.  
  341.     
  342.     def _call_chain(self, chain, kind, meth_name, *args):
  343.         handlers = chain.get(kind, ())
  344.         for handler in handlers:
  345.             func = getattr(handler, meth_name)
  346.             result = func(*args)
  347.             if result is not None:
  348.                 return result
  349.                 continue
  350.         
  351.  
  352.     
  353.     def open(self, fullurl, data = None):
  354.         if isinstance(fullurl, basestring):
  355.             req = Request(fullurl, data)
  356.         else:
  357.             req = fullurl
  358.             if data is not None:
  359.                 req.add_data(data)
  360.             
  361.         protocol = req.get_type()
  362.         meth_name = protocol + '_request'
  363.         for processor in self.process_request.get(protocol, []):
  364.             meth = getattr(processor, meth_name)
  365.             req = meth(req)
  366.         
  367.         response = self._open(req, data)
  368.         meth_name = protocol + '_response'
  369.         for processor in self.process_response.get(protocol, []):
  370.             meth = getattr(processor, meth_name)
  371.             response = meth(req, response)
  372.         
  373.         return response
  374.  
  375.     
  376.     def _open(self, req, data = None):
  377.         result = self._call_chain(self.handle_open, 'default', 'default_open', req)
  378.         if result:
  379.             return result
  380.         
  381.         protocol = req.get_type()
  382.         result = self._call_chain(self.handle_open, protocol, protocol + '_open', req)
  383.         if result:
  384.             return result
  385.         
  386.         return self._call_chain(self.handle_open, 'unknown', 'unknown_open', req)
  387.  
  388.     
  389.     def error(self, proto, *args):
  390.         if proto in ('http', 'https'):
  391.             dict = self.handle_error['http']
  392.             proto = args[2]
  393.             meth_name = 'http_error_%s' % proto
  394.             http_err = 1
  395.             orig_args = args
  396.         else:
  397.             dict = self.handle_error
  398.             meth_name = proto + '_error'
  399.             http_err = 0
  400.         args = (dict, proto, meth_name) + args
  401.         result = self._call_chain(*args)
  402.         if result:
  403.             return result
  404.         
  405.         if http_err:
  406.             args = (dict, 'default', 'http_error_default') + orig_args
  407.             return self._call_chain(*args)
  408.         
  409.  
  410.  
  411.  
  412. def build_opener(*handlers):
  413.     '''Create an opener object from a list of handlers.
  414.  
  415.     The opener will use several default handlers, including support
  416.     for HTTP and FTP.
  417.  
  418.     If any of the handlers passed as arguments are subclasses of the
  419.     default handlers, the default handlers will not be used.
  420.     '''
  421.     import types
  422.     
  423.     def isclass(obj):
  424.         if not isinstance(obj, types.ClassType):
  425.             pass
  426.         return hasattr(obj, '__bases__')
  427.  
  428.     opener = OpenerDirector()
  429.     default_classes = [
  430.         ProxyHandler,
  431.         UnknownHandler,
  432.         HTTPHandler,
  433.         HTTPDefaultErrorHandler,
  434.         HTTPRedirectHandler,
  435.         FTPHandler,
  436.         FileHandler,
  437.         HTTPErrorProcessor]
  438.     if hasattr(httplib, 'HTTPS'):
  439.         default_classes.append(HTTPSHandler)
  440.     
  441.     skip = []
  442.     for klass in default_classes:
  443.         for check in handlers:
  444.             if isclass(check):
  445.                 if issubclass(check, klass):
  446.                     skip.append(klass)
  447.                 
  448.             issubclass(check, klass)
  449.             if isinstance(check, klass):
  450.                 skip.append(klass)
  451.                 continue
  452.         
  453.     
  454.     for klass in skip:
  455.         default_classes.remove(klass)
  456.     
  457.     for klass in default_classes:
  458.         opener.add_handler(klass())
  459.     
  460.     for h in handlers:
  461.         if isclass(h):
  462.             h = h()
  463.         
  464.         opener.add_handler(h)
  465.     
  466.     return opener
  467.  
  468.  
  469. class BaseHandler:
  470.     handler_order = 500
  471.     
  472.     def add_parent(self, parent):
  473.         self.parent = parent
  474.  
  475.     
  476.     def close(self):
  477.         pass
  478.  
  479.     
  480.     def __lt__(self, other):
  481.         if not hasattr(other, 'handler_order'):
  482.             return True
  483.         
  484.         return self.handler_order < other.handler_order
  485.  
  486.  
  487.  
  488. class HTTPErrorProcessor(BaseHandler):
  489.     '''Process HTTP error responses.'''
  490.     handler_order = 1000
  491.     
  492.     def http_response(self, request, response):
  493.         code = response.code
  494.         msg = response.msg
  495.         hdrs = response.info()
  496.         if code not in (200, 206):
  497.             response = self.parent.error('http', request, response, code, msg, hdrs)
  498.         
  499.         return response
  500.  
  501.     https_response = http_response
  502.  
  503.  
  504. class HTTPDefaultErrorHandler(BaseHandler):
  505.     
  506.     def http_error_default(self, req, fp, code, msg, hdrs):
  507.         raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  508.  
  509.  
  510.  
  511. class HTTPRedirectHandler(BaseHandler):
  512.     max_repeats = 4
  513.     max_redirections = 10
  514.     
  515.     def redirect_request(self, req, fp, code, msg, headers, newurl):
  516.         """Return a Request or None in response to a redirect.
  517.  
  518.         This is called by the http_error_30x methods when a
  519.         redirection response is received.  If a redirection should
  520.         take place, return a new Request to allow http_error_30x to
  521.         perform the redirect.  Otherwise, raise HTTPError if no-one
  522.         else should try to handle this url.  Return None if you can't
  523.         but another Handler might.
  524.         """
  525.         m = req.get_method()
  526.         if (code in (301, 302, 303, 307) or m in ('GET', 'HEAD') or code in (301, 302, 303)) and m == 'POST':
  527.             newurl = newurl.replace(' ', '%20')
  528.             return Request(newurl, headers = req.headers, origin_req_host = req.get_origin_req_host(), unverifiable = True)
  529.         else:
  530.             raise HTTPError(req.get_full_url(), code, msg, headers, fp)
  531.  
  532.     
  533.     def http_error_302(self, req, fp, code, msg, headers):
  534.         if 'location' in headers:
  535.             newurl = headers.getheaders('location')[0]
  536.         elif 'uri' in headers:
  537.             newurl = headers.getheaders('uri')[0]
  538.         else:
  539.             return None
  540.         newurl = urlparse.urljoin(req.get_full_url(), newurl)
  541.         new = self.redirect_request(req, fp, code, msg, headers, newurl)
  542.         if new is None:
  543.             return None
  544.         
  545.         if hasattr(req, 'redirect_dict'):
  546.             visited = new.redirect_dict = req.redirect_dict
  547.             if visited.get(newurl, 0) >= self.max_repeats or len(visited) >= self.max_redirections:
  548.                 raise HTTPError(req.get_full_url(), code, self.inf_msg + msg, headers, fp)
  549.             
  550.         else:
  551.             visited = new.redirect_dict = req.redirect_dict = { }
  552.         visited[newurl] = visited.get(newurl, 0) + 1
  553.         fp.read()
  554.         fp.close()
  555.         return self.parent.open(new)
  556.  
  557.     http_error_301 = http_error_303 = http_error_307 = http_error_302
  558.     inf_msg = 'The HTTP server returned a redirect error that would lead to an infinite loop.\nThe last 30x error message was:\n'
  559.  
  560.  
  561. def _parse_proxy(proxy):
  562.     """Return (scheme, user, password, host/port) given a URL or an authority.
  563.  
  564.     If a URL is supplied, it must have an authority (host:port) component.
  565.     According to RFC 3986, having an authority component means the URL must
  566.     have two slashes after the scheme:
  567.  
  568.     >>> _parse_proxy('file:/ftp.example.com/')
  569.     Traceback (most recent call last):
  570.     ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
  571.  
  572.     The first three items of the returned tuple may be None.
  573.  
  574.     Examples of authority parsing:
  575.  
  576.     >>> _parse_proxy('proxy.example.com')
  577.     (None, None, None, 'proxy.example.com')
  578.     >>> _parse_proxy('proxy.example.com:3128')
  579.     (None, None, None, 'proxy.example.com:3128')
  580.  
  581.     The authority component may optionally include userinfo (assumed to be
  582.     username:password):
  583.  
  584.     >>> _parse_proxy('joe:password@proxy.example.com')
  585.     (None, 'joe', 'password', 'proxy.example.com')
  586.     >>> _parse_proxy('joe:password@proxy.example.com:3128')
  587.     (None, 'joe', 'password', 'proxy.example.com:3128')
  588.  
  589.     Same examples, but with URLs instead:
  590.  
  591.     >>> _parse_proxy('http://proxy.example.com/')
  592.     ('http', None, None, 'proxy.example.com')
  593.     >>> _parse_proxy('http://proxy.example.com:3128/')
  594.     ('http', None, None, 'proxy.example.com:3128')
  595.     >>> _parse_proxy('http://joe:password@proxy.example.com/')
  596.     ('http', 'joe', 'password', 'proxy.example.com')
  597.     >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
  598.     ('http', 'joe', 'password', 'proxy.example.com:3128')
  599.  
  600.     Everything after the authority is ignored:
  601.  
  602.     >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
  603.     ('ftp', 'joe', 'password', 'proxy.example.com')
  604.  
  605.     Test for no trailing '/' case:
  606.  
  607.     >>> _parse_proxy('http://joe:password@proxy.example.com')
  608.     ('http', 'joe', 'password', 'proxy.example.com')
  609.  
  610.     """
  611.     (scheme, r_scheme) = splittype(proxy)
  612.     if not r_scheme.startswith('/'):
  613.         scheme = None
  614.         authority = proxy
  615.     elif not r_scheme.startswith('//'):
  616.         raise ValueError('proxy URL with no authority: %r' % proxy)
  617.     
  618.     end = r_scheme.find('/', 2)
  619.     if end == -1:
  620.         end = None
  621.     
  622.     authority = r_scheme[2:end]
  623.     (userinfo, hostport) = splituser(authority)
  624.     if userinfo is not None:
  625.         (user, password) = splitpasswd(userinfo)
  626.     else:
  627.         user = password = None
  628.     return (scheme, user, password, hostport)
  629.  
  630.  
  631. class ProxyHandler(BaseHandler):
  632.     handler_order = 100
  633.     
  634.     def __init__(self, proxies = None):
  635.         if proxies is None:
  636.             proxies = getproxies()
  637.         
  638.         if not hasattr(proxies, 'has_key'):
  639.             raise AssertionError, 'proxies must be a mapping'
  640.         self.proxies = proxies
  641.         for type, url in proxies.items():
  642.             setattr(self, '%s_open' % type, (lambda r, proxy = url, type = type, meth = self.proxy_open: meth(r, proxy, type)))
  643.         
  644.  
  645.     
  646.     def proxy_open(self, req, proxy, type):
  647.         orig_type = req.get_type()
  648.         (proxy_type, user, password, hostport) = _parse_proxy(proxy)
  649.         if proxy_type is None:
  650.             proxy_type = orig_type
  651.         
  652.         if user and password:
  653.             user_pass = '%s:%s' % (unquote(user), unquote(password))
  654.             creds = base64.encodestring(user_pass).strip()
  655.             req.add_header('Proxy-authorization', 'Basic ' + creds)
  656.         
  657.         hostport = unquote(hostport)
  658.         req.set_proxy(hostport, proxy_type)
  659.         if orig_type == proxy_type:
  660.             return None
  661.         else:
  662.             return self.parent.open(req)
  663.  
  664.  
  665.  
  666. class HTTPPasswordMgr:
  667.     
  668.     def __init__(self):
  669.         self.passwd = { }
  670.  
  671.     
  672.     def add_password(self, realm, uri, user, passwd):
  673.         if isinstance(uri, basestring):
  674.             uri = [
  675.                 uri]
  676.         
  677.         if realm not in self.passwd:
  678.             self.passwd[realm] = { }
  679.         
  680.         for default_port in (True, False):
  681.             reduced_uri = []([ self.reduce_uri(u, default_port) for u in uri ])
  682.             self.passwd[realm][reduced_uri] = (user, passwd)
  683.         
  684.  
  685.     
  686.     def find_user_password(self, realm, authuri):
  687.         domains = self.passwd.get(realm, { })
  688.         for default_port in (True, False):
  689.             reduced_authuri = self.reduce_uri(authuri, default_port)
  690.             for uris, authinfo in domains.iteritems():
  691.                 for uri in uris:
  692.                     if self.is_suburi(uri, reduced_authuri):
  693.                         return authinfo
  694.                         continue
  695.                 
  696.             
  697.         
  698.         return (None, None)
  699.  
  700.     
  701.     def reduce_uri(self, uri, default_port = True):
  702.         '''Accept authority or URI and extract only the authority and path.'''
  703.         parts = urlparse.urlsplit(uri)
  704.         if parts[1]:
  705.             scheme = parts[0]
  706.             authority = parts[1]
  707.             if not parts[2]:
  708.                 pass
  709.             path = '/'
  710.         else:
  711.             scheme = None
  712.             authority = uri
  713.             path = '/'
  714.         (host, port) = splitport(authority)
  715.         if default_port and port is None and scheme is not None:
  716.             dport = {
  717.                 'http': 80,
  718.                 'https': 443 }.get(scheme)
  719.             if dport is not None:
  720.                 authority = '%s:%d' % (host, dport)
  721.             
  722.         
  723.         return (authority, path)
  724.  
  725.     
  726.     def is_suburi(self, base, test):
  727.         '''Check if test is below base in a URI tree
  728.  
  729.         Both args must be URIs in reduced form.
  730.         '''
  731.         if base == test:
  732.             return True
  733.         
  734.         if base[0] != test[0]:
  735.             return False
  736.         
  737.         common = posixpath.commonprefix((base[1], test[1]))
  738.         if len(common) == len(base[1]):
  739.             return True
  740.         
  741.         return False
  742.  
  743.  
  744.  
  745. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  746.     
  747.     def find_user_password(self, realm, authuri):
  748.         (user, password) = HTTPPasswordMgr.find_user_password(self, realm, authuri)
  749.         if user is not None:
  750.             return (user, password)
  751.         
  752.         return HTTPPasswordMgr.find_user_password(self, None, authuri)
  753.  
  754.  
  755.  
  756. class AbstractBasicAuthHandler:
  757.     rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
  758.     
  759.     def __init__(self, password_mgr = None):
  760.         if password_mgr is None:
  761.             password_mgr = HTTPPasswordMgr()
  762.         
  763.         self.passwd = password_mgr
  764.         self.add_password = self.passwd.add_password
  765.  
  766.     
  767.     def http_error_auth_reqed(self, authreq, host, req, headers):
  768.         authreq = headers.get(authreq, None)
  769.         if authreq:
  770.             mo = AbstractBasicAuthHandler.rx.search(authreq)
  771.             if mo:
  772.                 (scheme, realm) = mo.groups()
  773.                 if scheme.lower() == 'basic':
  774.                     return self.retry_http_basic_auth(host, req, realm)
  775.                 
  776.             
  777.         
  778.  
  779.     
  780.     def retry_http_basic_auth(self, host, req, realm):
  781.         (user, pw) = self.passwd.find_user_password(realm, host)
  782.         if pw is not None:
  783.             raw = '%s:%s' % (user, pw)
  784.             auth = 'Basic %s' % base64.encodestring(raw).strip()
  785.             if req.headers.get(self.auth_header, None) == auth:
  786.                 return None
  787.             
  788.             req.add_header(self.auth_header, auth)
  789.             return self.parent.open(req)
  790.         else:
  791.             return None
  792.  
  793.  
  794.  
  795. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  796.     auth_header = 'Authorization'
  797.     
  798.     def http_error_401(self, req, fp, code, msg, headers):
  799.         url = req.get_full_url()
  800.         return self.http_error_auth_reqed('www-authenticate', url, req, headers)
  801.  
  802.  
  803.  
  804. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  805.     auth_header = 'Proxy-authorization'
  806.     
  807.     def http_error_407(self, req, fp, code, msg, headers):
  808.         authority = req.get_host()
  809.         return self.http_error_auth_reqed('proxy-authenticate', authority, req, headers)
  810.  
  811.  
  812.  
  813. def randombytes(n):
  814.     '''Return n random bytes.'''
  815.     pass
  816.  
  817.  
  818. class AbstractDigestAuthHandler:
  819.     
  820.     def __init__(self, passwd = None):
  821.         if passwd is None:
  822.             passwd = HTTPPasswordMgr()
  823.         
  824.         self.passwd = passwd
  825.         self.add_password = self.passwd.add_password
  826.         self.retried = 0
  827.         self.nonce_count = 0
  828.  
  829.     
  830.     def reset_retry_count(self):
  831.         self.retried = 0
  832.  
  833.     
  834.     def http_error_auth_reqed(self, auth_header, host, req, headers):
  835.         authreq = headers.get(auth_header, None)
  836.         if authreq:
  837.             scheme = authreq.split()[0]
  838.             if scheme.lower() == 'digest':
  839.                 return self.retry_http_digest_auth(req, authreq)
  840.             
  841.         
  842.  
  843.     
  844.     def retry_http_digest_auth(self, req, auth):
  845.         (token, challenge) = auth.split(' ', 1)
  846.         chal = parse_keqv_list(parse_http_list(challenge))
  847.         auth = self.get_authorization(req, chal)
  848.         if auth:
  849.             auth_val = 'Digest %s' % auth
  850.             if req.headers.get(self.auth_header, None) == auth_val:
  851.                 return None
  852.             
  853.             req.add_unredirected_header(self.auth_header, auth_val)
  854.             resp = self.parent.open(req)
  855.             return resp
  856.         
  857.  
  858.     
  859.     def get_cnonce(self, nonce):
  860.         dig = hashlib.sha1('%s:%s:%s:%s' % (self.nonce_count, nonce, time.ctime(), randombytes(8))).hexdigest()
  861.         return dig[:16]
  862.  
  863.     
  864.     def get_authorization(self, req, chal):
  865.         
  866.         try:
  867.             realm = chal['realm']
  868.             nonce = chal['nonce']
  869.             qop = chal.get('qop')
  870.             algorithm = chal.get('algorithm', 'MD5')
  871.             opaque = chal.get('opaque', None)
  872.         except KeyError:
  873.             return None
  874.  
  875.         (H, KD) = self.get_algorithm_impls(algorithm)
  876.         if H is None:
  877.             return None
  878.         
  879.         (user, pw) = self.passwd.find_user_password(realm, req.get_full_url())
  880.         if user is None:
  881.             return None
  882.         
  883.         if req.has_data():
  884.             entdig = self.get_entity_digest(req.get_data(), chal)
  885.         else:
  886.             entdig = None
  887.         A1 = '%s:%s:%s' % (user, realm, pw)
  888.         A2 = '%s:%s' % (req.get_method(), req.get_selector())
  889.         if qop == 'auth':
  890.             self.nonce_count += 1
  891.             ncvalue = '%08x' % self.nonce_count
  892.             cnonce = self.get_cnonce(nonce)
  893.             noncebit = '%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, qop, H(A2))
  894.             respdig = KD(H(A1), noncebit)
  895.         elif qop is None:
  896.             respdig = KD(H(A1), '%s:%s' % (nonce, H(A2)))
  897.         
  898.         base = 'username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, nonce, req.get_selector(), respdig)
  899.         if opaque:
  900.             base += ', opaque="%s"' % opaque
  901.         
  902.         if entdig:
  903.             base += ', digest="%s"' % entdig
  904.         
  905.         base += ', algorithm="%s"' % algorithm
  906.         if qop:
  907.             base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  908.         
  909.         return base
  910.  
  911.     
  912.     def get_algorithm_impls(self, algorithm):
  913.         if algorithm == 'MD5':
  914.             
  915.             H = lambda x: hashlib.md5(x).hexdigest()
  916.         elif algorithm == 'SHA':
  917.             
  918.             H = lambda x: hashlib.sha1(x).hexdigest()
  919.         
  920.         
  921.         KD = lambda s, d: H('%s:%s' % (s, d))
  922.         return (H, KD)
  923.  
  924.     
  925.     def get_entity_digest(self, data, chal):
  926.         pass
  927.  
  928.  
  929.  
  930. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  931.     '''An authentication protocol defined by RFC 2069
  932.  
  933.     Digest authentication improves on basic authentication because it
  934.     does not transmit passwords in the clear.
  935.     '''
  936.     auth_header = 'Authorization'
  937.     handler_order = 490
  938.     
  939.     def http_error_401(self, req, fp, code, msg, headers):
  940.         host = urlparse.urlparse(req.get_full_url())[1]
  941.         retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  942.         self.reset_retry_count()
  943.         return retry
  944.  
  945.  
  946.  
  947. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  948.     auth_header = 'Proxy-Authorization'
  949.     handler_order = 490
  950.     
  951.     def http_error_407(self, req, fp, code, msg, headers):
  952.         host = req.get_host()
  953.         retry = self.http_error_auth_reqed('proxy-authenticate', host, req, headers)
  954.         self.reset_retry_count()
  955.         return retry
  956.  
  957.  
  958.  
  959. class AbstractHTTPHandler(BaseHandler):
  960.     
  961.     def __init__(self, debuglevel = 0):
  962.         self._debuglevel = debuglevel
  963.  
  964.     
  965.     def set_http_debuglevel(self, level):
  966.         self._debuglevel = level
  967.  
  968.     
  969.     def do_request_(self, request):
  970.         host = request.get_host()
  971.         if not host:
  972.             raise URLError('no host given')
  973.         
  974.         if request.has_data():
  975.             data = request.get_data()
  976.             if not request.has_header('Content-type'):
  977.                 request.add_unredirected_header('Content-type', 'application/x-www-form-urlencoded')
  978.             
  979.             if not request.has_header('Content-length'):
  980.                 request.add_unredirected_header('Content-length', '%d' % len(data))
  981.             
  982.         
  983.         (scheme, sel) = splittype(request.get_selector())
  984.         (sel_host, sel_path) = splithost(sel)
  985.         if not request.has_header('Host'):
  986.             if not sel_host:
  987.                 pass
  988.             request.add_unredirected_header('Host', host)
  989.         
  990.         for name, value in self.parent.addheaders:
  991.             name = name.capitalize()
  992.             if not request.has_header(name):
  993.                 request.add_unredirected_header(name, value)
  994.                 continue
  995.         
  996.         return request
  997.  
  998.     
  999.     def do_open(self, http_class, req):
  1000.         '''Return an addinfourl object for the request, using http_class.
  1001.  
  1002.         http_class must implement the HTTPConnection API from httplib.
  1003.         The addinfourl return value is a file-like object.  It also
  1004.         has methods and attributes including:
  1005.             - info(): return a mimetools.Message object for the headers
  1006.             - geturl(): return the original request URL
  1007.             - code: HTTP status code
  1008.         '''
  1009.         host = req.get_host()
  1010.         if not host:
  1011.             raise URLError('no host given')
  1012.         
  1013.         h = http_class(host)
  1014.         h.set_debuglevel(self._debuglevel)
  1015.         headers = dict(req.headers)
  1016.         headers.update(req.unredirected_hdrs)
  1017.         headers['Connection'] = 'close'
  1018.         headers = dict((lambda .0: for name, val in .0:
  1019. (name.title(), val))(headers.items()))
  1020.         
  1021.         try:
  1022.             h.request(req.get_method(), req.get_selector(), req.data, headers)
  1023.             r = h.getresponse()
  1024.         except socket.error:
  1025.             err = None
  1026.             raise URLError(err)
  1027.  
  1028.         r.recv = r.read
  1029.         fp = socket._fileobject(r)
  1030.         resp = addinfourl(fp, r.msg, req.get_full_url())
  1031.         resp.code = r.status
  1032.         resp.msg = r.reason
  1033.         return resp
  1034.  
  1035.  
  1036.  
  1037. class HTTPHandler(AbstractHTTPHandler):
  1038.     
  1039.     def http_open(self, req):
  1040.         return self.do_open(httplib.HTTPConnection, req)
  1041.  
  1042.     http_request = AbstractHTTPHandler.do_request_
  1043.  
  1044. if hasattr(httplib, 'HTTPS'):
  1045.     
  1046.     class HTTPSHandler(AbstractHTTPHandler):
  1047.         
  1048.         def https_open(self, req):
  1049.             return self.do_open(httplib.HTTPSConnection, req)
  1050.  
  1051.         https_request = AbstractHTTPHandler.do_request_
  1052.  
  1053.  
  1054.  
  1055. class HTTPCookieProcessor(BaseHandler):
  1056.     
  1057.     def __init__(self, cookiejar = None):
  1058.         import cookielib
  1059.         if cookiejar is None:
  1060.             cookiejar = cookielib.CookieJar()
  1061.         
  1062.         self.cookiejar = cookiejar
  1063.  
  1064.     
  1065.     def http_request(self, request):
  1066.         self.cookiejar.add_cookie_header(request)
  1067.         return request
  1068.  
  1069.     
  1070.     def http_response(self, request, response):
  1071.         self.cookiejar.extract_cookies(response, request)
  1072.         return response
  1073.  
  1074.     https_request = http_request
  1075.     https_response = http_response
  1076.  
  1077.  
  1078. class UnknownHandler(BaseHandler):
  1079.     
  1080.     def unknown_open(self, req):
  1081.         type = req.get_type()
  1082.         raise URLError('unknown url type: %s' % type)
  1083.  
  1084.  
  1085.  
  1086. def parse_keqv_list(l):
  1087.     '''Parse list of key=value strings where keys are not duplicated.'''
  1088.     parsed = { }
  1089.     for elt in l:
  1090.         (k, v) = elt.split('=', 1)
  1091.         if v[0] == '"' and v[-1] == '"':
  1092.             v = v[1:-1]
  1093.         
  1094.         parsed[k] = v
  1095.     
  1096.     return parsed
  1097.  
  1098.  
  1099. def parse_http_list(s):
  1100.     '''Parse lists as described by RFC 2068 Section 2.
  1101.  
  1102.     In particular, parse comma-separated lists where the elements of
  1103.     the list may include quoted-strings.  A quoted-string could
  1104.     contain a comma.  A non-quoted string could have quotes in the
  1105.     middle.  Neither commas nor quotes count if they are escaped.
  1106.     Only double-quotes count, not single-quotes.
  1107.     '''
  1108.     res = []
  1109.     part = ''
  1110.     escape = quote = False
  1111.     for cur in s:
  1112.         if escape:
  1113.             part += cur
  1114.             escape = False
  1115.             continue
  1116.         
  1117.         if quote:
  1118.             if cur == '\\':
  1119.                 escape = True
  1120.                 continue
  1121.             elif cur == '"':
  1122.                 quote = False
  1123.             
  1124.             part += cur
  1125.             continue
  1126.         
  1127.         if cur == ',':
  1128.             res.append(part)
  1129.             part = ''
  1130.             continue
  1131.         
  1132.         if cur == '"':
  1133.             quote = True
  1134.         
  1135.         part += cur
  1136.     
  1137.     if part:
  1138.         res.append(part)
  1139.     
  1140.     return [ part.strip() for part in res ]
  1141.  
  1142.  
  1143. class FileHandler(BaseHandler):
  1144.     
  1145.     def file_open(self, req):
  1146.         url = req.get_selector()
  1147.         if url[:2] == '//' and url[2:3] != '/':
  1148.             req.type = 'ftp'
  1149.             return self.parent.open(req)
  1150.         else:
  1151.             return self.open_local_file(req)
  1152.  
  1153.     names = None
  1154.     
  1155.     def get_names(self):
  1156.         if FileHandler.names is None:
  1157.             
  1158.             try:
  1159.                 FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname()))
  1160.             except socket.gaierror:
  1161.                 FileHandler.names = (socket.gethostbyname('localhost'),)
  1162.             except:
  1163.                 None<EXCEPTION MATCH>socket.gaierror
  1164.             
  1165.  
  1166.         None<EXCEPTION MATCH>socket.gaierror
  1167.         return FileHandler.names
  1168.  
  1169.     
  1170.     def open_local_file(self, req):
  1171.         import email.Utils as email
  1172.         import mimetypes
  1173.         host = req.get_host()
  1174.         file = req.get_selector()
  1175.         localfile = url2pathname(file)
  1176.         stats = os.stat(localfile)
  1177.         size = stats.st_size
  1178.         modified = email.Utils.formatdate(stats.st_mtime, usegmt = True)
  1179.         mtype = mimetypes.guess_type(file)[0]
  1180.         if not mtype:
  1181.             pass
  1182.         headers = mimetools.Message(StringIO('Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  1183.         if host:
  1184.             (host, port) = splitport(host)
  1185.         
  1186.         if (not host or not port) and socket.gethostbyname(host) in self.get_names():
  1187.             return addinfourl(open(localfile, 'rb'), headers, 'file:' + file)
  1188.         
  1189.         raise URLError('file not on local host')
  1190.  
  1191.  
  1192.  
  1193. class FTPHandler(BaseHandler):
  1194.     
  1195.     def ftp_open(self, req):
  1196.         import ftplib
  1197.         import mimetypes
  1198.         host = req.get_host()
  1199.         if not host:
  1200.             raise IOError, ('ftp error', 'no host given')
  1201.         
  1202.         (host, port) = splitport(host)
  1203.         if port is None:
  1204.             port = ftplib.FTP_PORT
  1205.         else:
  1206.             port = int(port)
  1207.         (user, host) = splituser(host)
  1208.         if user:
  1209.             (user, passwd) = splitpasswd(user)
  1210.         else:
  1211.             passwd = None
  1212.         host = unquote(host)
  1213.         if not user:
  1214.             pass
  1215.         user = unquote('')
  1216.         if not passwd:
  1217.             pass
  1218.         passwd = unquote('')
  1219.         
  1220.         try:
  1221.             host = socket.gethostbyname(host)
  1222.         except socket.error:
  1223.             msg = None
  1224.             raise URLError(msg)
  1225.  
  1226.         (path, attrs) = splitattr(req.get_selector())
  1227.         dirs = path.split('/')
  1228.         dirs = map(unquote, dirs)
  1229.         dirs = dirs[:-1]
  1230.         file = dirs[-1]
  1231.         if dirs and not dirs[0]:
  1232.             dirs = dirs[1:]
  1233.         
  1234.         
  1235.         try:
  1236.             fw = self.connect_ftp(user, passwd, host, port, dirs)
  1237.             if not file or 'I':
  1238.                 pass
  1239.             type = 'D'
  1240.             for attr in attrs:
  1241.                 (attr, value) = splitvalue(attr)
  1242.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1243.                     type = value.upper()
  1244.                     continue
  1245.             
  1246.             (fp, retrlen) = fw.retrfile(file, type)
  1247.             headers = ''
  1248.             mtype = mimetypes.guess_type(req.get_full_url())[0]
  1249.             if mtype:
  1250.                 headers += 'Content-type: %s\n' % mtype
  1251.             
  1252.             if retrlen is not None and retrlen >= 0:
  1253.                 headers += 'Content-length: %d\n' % retrlen
  1254.             
  1255.             sf = StringIO(headers)
  1256.             headers = mimetools.Message(sf)
  1257.             return addinfourl(fp, headers, req.get_full_url())
  1258.         except ftplib.all_errors:
  1259.             msg = None
  1260.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  1261.  
  1262.  
  1263.     
  1264.     def connect_ftp(self, user, passwd, host, port, dirs):
  1265.         fw = ftpwrapper(user, passwd, host, port, dirs)
  1266.         return fw
  1267.  
  1268.  
  1269.  
  1270. class CacheFTPHandler(FTPHandler):
  1271.     
  1272.     def __init__(self):
  1273.         self.cache = { }
  1274.         self.timeout = { }
  1275.         self.soonest = 0
  1276.         self.delay = 60
  1277.         self.max_conns = 16
  1278.  
  1279.     
  1280.     def setTimeout(self, t):
  1281.         self.delay = t
  1282.  
  1283.     
  1284.     def setMaxConns(self, m):
  1285.         self.max_conns = m
  1286.  
  1287.     
  1288.     def connect_ftp(self, user, passwd, host, port, dirs):
  1289.         key = (user, host, port, '/'.join(dirs))
  1290.         if key in self.cache:
  1291.             self.timeout[key] = time.time() + self.delay
  1292.         else:
  1293.             self.cache[key] = ftpwrapper(user, passwd, host, port, dirs)
  1294.             self.timeout[key] = time.time() + self.delay
  1295.         self.check_cache()
  1296.         return self.cache[key]
  1297.  
  1298.     
  1299.     def check_cache(self):
  1300.         t = time.time()
  1301.         if self.soonest <= t:
  1302.             for k, v in self.timeout.items():
  1303.                 if v < t:
  1304.                     self.cache[k].close()
  1305.                     del self.cache[k]
  1306.                     del self.timeout[k]
  1307.                     continue
  1308.             
  1309.         
  1310.         self.soonest = min(self.timeout.values())
  1311.         if len(self.cache) == self.max_conns:
  1312.             for k, v in self.timeout.items():
  1313.                 if v == self.soonest:
  1314.                     del self.cache[k]
  1315.                     del self.timeout[k]
  1316.                     break
  1317.                     continue
  1318.             
  1319.             self.soonest = min(self.timeout.values())
  1320.         
  1321.  
  1322.  
  1323.  
  1324. class GopherHandler(BaseHandler):
  1325.     
  1326.     def gopher_open(self, req):
  1327.         import gopherlib
  1328.         host = req.get_host()
  1329.         if not host:
  1330.             raise GopherError('no host given')
  1331.         
  1332.         host = unquote(host)
  1333.         selector = req.get_selector()
  1334.         (type, selector) = splitgophertype(selector)
  1335.         (selector, query) = splitquery(selector)
  1336.         selector = unquote(selector)
  1337.         if query:
  1338.             query = unquote(query)
  1339.             fp = gopherlib.send_query(selector, query, host)
  1340.         else:
  1341.             fp = gopherlib.send_selector(selector, host)
  1342.         return addinfourl(fp, noheaders(), req.get_full_url())
  1343.  
  1344.  
  1345.